package com.hua.yuan.live.fragment;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.hua.yuan.BaseFragment;
import com.hua.yuan.dialog.ConfirmCancelDialog;
import com.hua.yuan.live.LiveModule;
import com.hua.yuan.live.LivePlayActivity;
import com.hua.yuan.live.R;
import com.hua.yuan.live.adapter.LiveHistoryAdapter;
import com.hua.yuan.live.listener.OnBuyClickListener;
import com.hua.yuan.live.repertory.cloud_data.loader.LiveHistoryLoader;
import com.hua.yuan.live.repertory.cloud_data.loader.LiveReservationLoader;
import com.hua.yuan.live.repertory.cloud_data.res.LiveHistoryComband;
import com.hua.yuan.live.repertory.cloud_data.res.LiveVideoBean;
import com.hua.yuan.live.repertory.cloud_data.res.ResercationBean;
import com.hua.yuan.live.repertory.cloud_data.res.ResultMsg;
import com.hua.yuan.live.view.BlackView;
import com.hua.yuan.live.view.anchor.HistoryView;

import java.util.List;

/**
 * 主播历史记录页面
 */
public class AnchorHistoryFragment extends BaseFragment implements
        LoaderManager.LoaderCallbacks<LiveHistoryComband>,
        OnBuyClickListener,
        ConfirmCancelDialog.OnConfirmListener,
        LiveHistoryLoader.OnPlayVideoCallback
{

    private LiveHistoryLoader mLoader;

    private String mToken;

    private int pAnchorId;

    private int mMoney;

    private ConfirmCancelDialog mConfigDialog;

    private LiveVideoBean mCurrentVideo;

    private HistoryView mHistoryView;

    private BlackView mBlackView;

    private ViewGroup mView;

    public static AnchorHistoryFragment newInstance(String pToken,int pAnchordId){
        Bundle bundle=new Bundle();
        bundle.putInt(LiveModule.INTENT_ANCHOR_ID,pAnchordId);
        bundle.putString("TOKEN",pToken);
        AnchorHistoryFragment anchorHistoryFragment= new AnchorHistoryFragment();
        anchorHistoryFragment.setArguments(bundle);
        return anchorHistoryFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLoader=new LiveHistoryLoader();

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView= (ViewGroup) LayoutInflater.from(getContext()).inflate(R.layout.fragment_personal_history,null);
        initView(mView);
        initData();
        return mView;
    }


    private void initData(){
        mToken=getArguments().getString("TOKEN");
        int anchorId=getArguments().getInt(LiveModule.INTENT_ANCHOR_ID);
        mLoader.requestHistory(mToken,anchorId,0,10,this);
    }

    private void initView(View pView){
        mHistoryView=new HistoryView(getActivity(),pView,this);
        mBlackView=new BlackView(getActivity());
        mView.addView(mBlackView.getCurrentView());
        mBlackView.setTitle(getActivity().getResources().getString(R.string.common_loading_title));
        mBlackView.setSubTitle(getActivity().getResources().getString(R.string.common_loading_subtitle));

        mConfigDialog = ConfirmCancelDialog.create(getActivity().getSupportFragmentManager());
        mConfigDialog.setOnConfirmListener(this);
    }




    @NonNull
    @Override
    public Loader<LiveHistoryComband> onCreateLoader(int id, @Nullable Bundle args) {
        return null;
    }

    @Override
    public void onLoadFinished(@NonNull Loader<LiveHistoryComband> loader, LiveHistoryComband data) {

        if(data.getLiveVideoBean()==null || data.getLiveVideoBean().size()==0){
            mHistoryView.setVisible(View.GONE);
            mBlackView.setTitle(getActivity().getResources().getString(R.string.anchor_resume_black));
            mBlackView.setSubTitle(getActivity().getResources().getString(R.string.anchor_resume_black_subtitle));
            mBlackView.setVisible(View.VISIBLE);
            return;
        }
        mHistoryView.setVisible(View.VISIBLE);
        mHistoryView.setData(data);
        mBlackView.setVisible(View.GONE);
    }

    @Override
    public void onLoaderReset(@NonNull Loader<LiveHistoryComband> loader) {

    }

    @SuppressLint("StringFormatMatches")
    @Override
    public void click(int position) {
        if (position > mHistoryView.getData().size()) {
            return;
        }
        LiveVideoBean bean = (LiveVideoBean) mHistoryView.getData().get(position);
        mCurrentVideo=bean;
        if (bean == null) {
            return;
        }
        /**
         *判断是否收费
         */
        if(bean.getIsFree()==0){
            //判断是否付过费
            mLoader.requestByPlayVideoStatus(mToken,bean.getId(),this);
            return;
        }
        jumpPlayVideo();
    }

    @Override
    public void onConfirm(View v) {

        if(mMoney> Integer.parseInt(mCurrentVideo.getNowPrice())){

            //执行支付逻辑
            mLoader.playVideo(mToken,mCurrentVideo.getId(),mCurrentVideo.getNowPrice(),this);
        }else{
            Toast.makeText(getContext().getApplicationContext(),"余额不足了，跳转至我的钱包页面",Toast.LENGTH_SHORT).show();
            Intent intent = new Intent();
            intent.setClassName(getActivity(), "com.hua.yuan.ui.MoneyBagActivity");
            intent.putExtra("buyMoney",String.valueOf(mCurrentVideo.getNowPrice()));
            intent.putExtra("movieId",mCurrentVideo.getMovieAddress());
            intent.putExtra("isTuji",false);
            if (getActivity().getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
                startActivity(intent);
                return;
            }

        }

    }


    /**
     * 弹出对话框
     */
    private void jumpPlayDilaog(){

        if(!mConfigDialog.isAdded()) {
            mConfigDialog.setMoney(String.valueOf(mCurrentVideo.getNowPrice()),getActivity());
            mConfigDialog.show();
        }else{
            mConfigDialog.dismiss();
        }
    }

    @Override
    public void playVideoStatus(ResultMsg resultMsg) {
        //购买过了
        if(resultMsg.getErrNo()==0){
            jumpPlayVideo();
            return;
        }
        Toast.makeText(getContext().getApplicationContext(),resultMsg.getErrMsg(),Toast.LENGTH_SHORT).show();
        //未购买过，
        jumpPlayDilaog();
    }


    private void jumpPlayVideo(){

        if(mCurrentVideo.getMovieAddress()==null){
            return;
        }
        Intent intent = new Intent();
        intent.setClass(getActivity(),LivePlayActivity.class);
        intent.putExtra(LiveModule.INTENT_VIDEO_URL,mCurrentVideo.getMovieAddress());
        if (getActivity().getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
            startActivityForResult(intent,LiveModule.RESULT_ANCHOR_CODE);
            return;
        }
    }

    @Override
    public void onFailure(Throwable e) {

    }
}

